package com.example.yskjproject.ui.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.example.yskjproject.R;
import com.example.yskjproject.adapter.RechargeAmountAdapter;
import com.example.yskjproject.adapter.RechargeRecordAdapter;
import com.example.yskjproject.adapter.WithDrawalRecordAdapter;
import com.example.yskjproject.content.Content;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.APIService;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.inter.Refreshable;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.OrderListModel;
import com.example.yskjproject.model.RechargeModel;
import com.example.yskjproject.model.RechargeRecordListModel;
import com.example.yskjproject.model.WalletModel;
import com.example.yskjproject.model.WithDrawalRecordListModel;
import com.example.yskjproject.model.WxScanCodeModel;
import com.example.yskjproject.utils.EventBusUtil;
import com.example.yskjproject.utils.Log;
import com.example.yskjproject.view.dialog.PayDialog;
import com.example.yskjproject.view.dialog.WXCodeDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.Nullable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class WalletPageFragment extends Fragment implements RechargeAmountAdapter.OnRechargeAmountSelectedListener, Refreshable{
    private static final String ARG_POSITION = "position";
    private int position;
    private View walletPageFragment;
    private AppCompatTextView withdrawableBalance;
    private AppCompatTextView pendingBalance;
    private AppCompatTextView frozenBalance;
    private AppCompatTextView coinBalance;
    private AppCompatTextView balance;
    private AppCompatButton btnRecharge;
    private AppCompatButton btnWithDraw;
    private AppCompatButton btnBuyCoins;
    private AppCompatButton btnBuyCourse;
    private int mRechargeNum = 0;
    private RadioGroup mRechargeRadioGroup;
    private AppCompatButton mRechargeButton;
    private Gson gson = new Gson();
    private int mRechargeAmountId = 0;
    private AppCompatButton mBuyTokenButton;
    private AppCompatTextView mTokenDescribe;
    private AppCompatTextView mTvTokensAmount;
    private RecyclerView withDrawalRecyclerView;
    private WithDrawalRecordAdapter withDrawalRecordAdapter;
    private int virtualCoins;
    private String mRechargeAmount;
    private RecyclerView mRechargeAmountRecyclerView;
    private RechargeRecordAdapter mRechargeRecordAdapter;
    private AppCompatTextView accumulateWithDrawnAmount;
    private AlertDialog mPaydialogProgress;
    private AppCompatTextView wechatName;
    private View dialogView;
    private AlertDialog dialogProgress;
    private LinearLayout llDialog;
    private SwipeRefreshLayout rechargeSwipeRefreshLayout;
    private AppCompatTextView tvNoRecord;
    private SwipeRefreshLayout withDrawalSwipeRefreshLayout;
    private AppCompatTextView tvWithDrawalNoRecord;
    public static WalletPageFragment newInstance(int position) {
        WalletPageFragment fragment = new WalletPageFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_POSITION, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        position = getArguments() != null ? getArguments().getInt(ARG_POSITION) : 0;
        EventBusUtil.register(this);
        switch (position) {
            case 0: // 我的钱包
                walletPageFragment = inflater.inflate(R.layout.my_wallet_page_fragment, container, false);
                setupWalletPage(walletPageFragment);
                getWalletInfoDate();
                break;
            case 1: // 充值记录
                walletPageFragment = inflater.inflate(R.layout.recharge_record_page_fragment, container, false);
                setupRechargePage(walletPageFragment);
                break;
            case 2: // 提现记录
                walletPageFragment = inflater.inflate(R.layout.with_drawal_record_fragment, container, false);
                setupWithdrawPage(walletPageFragment);
                break;
            default:
                walletPageFragment = inflater.inflate(R.layout.my_wallet_page_fragment, container, false);
        }

        return walletPageFragment;
    }

    private void getWithDrawalInfoDate() {
        OkGo.<LzyResponse<WithDrawalRecordListModel>>get(Urls.WITHDRAWAL_RECORD + "?&page=" + Content.page + "&limit=" + Content.limit).execute(new JsonCallback<LzyResponse<WithDrawalRecordListModel>>() {
            @Override
            public void onSuccess(Response<LzyResponse<WithDrawalRecordListModel>> response) {
                WithDrawalRecordListModel withDrawalRecordModelList = response.body().data;
                if (!withDrawalRecordModelList.getList().isEmpty()) {
                    tvWithDrawalNoRecord.setVisibility(View.GONE);
                    withDrawalSwipeRefreshLayout.setVisibility(View.VISIBLE);
                } else {
                    tvWithDrawalNoRecord.setVisibility(View.VISIBLE);
                    withDrawalSwipeRefreshLayout.setVisibility(View.GONE);
                }
                if (!withDrawalRecordModelList.getList().isEmpty()) {
                    withDrawalRecordAdapter.addData(withDrawalRecordModelList);
                    withDrawalRecyclerView.setAdapter(withDrawalRecordAdapter);
                    withDrawalSwipeRefreshLayout.setRefreshing(false);
                } else {

                }

            }

            @Override
            public void onError(Response<LzyResponse<WithDrawalRecordListModel>> response) {
                super.onError(response);
                withDrawalSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * 获取充值页面信息（代币或实币）
     * */

    private void getRechargeInfoDate(int type) {
        OkGo.<LzyResponse<RechargeRecordListModel>>get(Urls.RECHARGE_LIST + "?type=" + type).execute(new JsonCallback<LzyResponse<RechargeRecordListModel>>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(Response<LzyResponse<RechargeRecordListModel>> response) {
                RechargeRecordListModel rechargeRecordListModel = response.body().data;
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

                if (rechargeRecordListModel.getList().get(0).getType() == 3) {
                    dialogView = getLayoutInflater().inflate(R.layout.recharge_dialog, null);
                    builder.setView(dialogView);
                    dialogProgress = builder.create();
                    dialogProgress.setCancelable(false);
                    mRechargeButton = dialogView.findViewById(R.id.recharge_button);
                    mRechargeButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            postRecharge(3, "wechat");
                        }
                    });
                } else {
                    dialogView = getLayoutInflater().inflate(R.layout.buy_tokens_dialog, null);
                    builder.setView(dialogView);
                    dialogProgress = builder.create();
                    dialogProgress.setCancelable(false);
                    mBuyTokenButton = dialogView.findViewById(R.id.buy_token_button);
                    mTokenDescribe = dialogView.findViewById(R.id.tv_token_describe);
                    mTvTokensAmount = dialogView.findViewById(R.id.tv_tokens_amount);
                    AppCompatTextView tokensPaymentMethod = dialogView.findViewById(R.id.tokens_payment_method);
                    tokensPaymentMethod.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //TODO 需要一个支付弹窗，用来选择用什么支付
//                            PayDialog payDialog = new PayDialog(this, String.valueOf(response));
//                            payDialog.show();
                        }
                    });
                    mTvTokensAmount.setText("代币余额: " + virtualCoins);

                    mBuyTokenButton.setOnClickListener(v -> {
                        if (Integer.parseInt(mRechargeAmount) > Integer.parseInt(balance.getText().toString())) {
                            postRecharge(2, "wechat");
                        } else {
                            postRecharge(2, "balance");
                        }
                    });
                }
                GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
                RecyclerView rlRechargeAmountList = dialogView.findViewById(R.id.rl_recharge_amount);
                rlRechargeAmountList.setLayoutManager(layoutManager);
                rlRechargeAmountList.setAdapter(new RechargeAmountAdapter(rechargeRecordListModel.getList(), WalletPageFragment.this));
                dialogProgress.setCancelable(true);
                dialogProgress.show();
            }

            @Override
            public void onError(Response<LzyResponse<RechargeRecordListModel>> response) {
                super.onError(response);
            }
        });
    }

    /**
     * 我的钱包页面逻辑处理
     */

    private void setupWalletPage(View view) {
        withdrawableBalance = view.findViewById(R.id.with_drawal_amount);//可提现金额
        pendingBalance = view.findViewById(R.id.pending_settlement_amount);//待结算金额
        frozenBalance = view.findViewById(R.id.withdraw_frozen_amount);//冻结金额
        coinBalance = view.findViewById(R.id.tv_coin_balance);//代币金额
        btnRecharge = view.findViewById(R.id.btn_recharge);//充值
        btnWithDraw = view.findViewById(R.id.btn_withdraw);//提现
        balance = view.findViewById(R.id.tv_balance);//余额
        btnBuyCoins = view.findViewById(R.id.btn_buy_coins);//购买代币
        btnBuyCourse = view.findViewById(R.id.btn_buy_course);//购买课程
        accumulateWithDrawnAmount = view.findViewById(R.id.accumulated_withdrawn_amount);
        RelativeLayout rlWechatManager = view.findViewById(R.id.rl_wechat_manager);
        wechatName = view.findViewById(R.id.wechat_name);
        rlWechatManager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getWxCodeDate();
            }
        });

        btnRecharge.setOnClickListener(v -> {
            getRechargeInfoDate(3);
        });
        btnWithDraw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                dialogView = getLayoutInflater().inflate(R.layout.withdrawal_dialog, null);
                builder.setView(dialogView);
                dialogProgress = builder.create();
                dialogProgress.setCancelable(true);
                dialogProgress.show();
                AppCompatTextView withdrawalAmount = dialogProgress.findViewById(R.id.withdrawal_amount);
                AppCompatEditText etInputMessage = dialogProgress.findViewById(R.id.et_input_message);
                AppCompatTextView allWithdrawal = dialogProgress.findViewById(R.id.all_withdrawal);
                withdrawalAmount.setText("¥" + balance.getText().toString());
                AppCompatButton withdrawalButton = dialogProgress.findViewById(R.id.withdrawal_button);
                allWithdrawal.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        etInputMessage.setText(balance.getText().toString());
                    }
                });
                withdrawalButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        withDrawablePay(etInputMessage.getText().toString());
                    }
                });


            }
        });
        btnBuyCoins.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getRechargeInfoDate(2);
            }
        });
        btnBuyCourse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

    private void getWxCodeDate() {
        Type type = new TypeToken<LzyResponse<WxScanCodeModel>>() {
        }.getType();
        APIService.<LzyResponse<WxScanCodeModel>>getData(type, Urls.WX_CODE).subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<WxScanCodeModel>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(WxScanCodeModel wxScanCodeModel) {
                if (TextUtils.isEmpty(wxScanCodeModel.getImg_url())) {
                    return;
                }
                WXCodeDialog wxCodeDialog = new WXCodeDialog(getContext(), wxScanCodeModel);
                wxCodeDialog.show();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取二维码失败");
            }

            @Override
            public void onComplete() {

            }
        }); //
    }


    /**
     * 支付按钮请求
     * */
    private void postRecharge(int rechargeType, String payType) {
        if (mRechargeAmountId == 0) {
            Toast.makeText(getContext(), "请选择充值金额", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("recharge_type", rechargeType);
        jsonParams.put("pay_type", payType);
        jsonParams.put("id", mRechargeAmountId);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse<RechargeModel>>post(Urls.RECHARGE_PAY).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<RechargeModel>>() {
            @Override
            public void onSuccess(Response<LzyResponse<RechargeModel>> response) {
                RechargeModel rechargeModel = response.body().data;
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                View dialogView;

                if (TextUtils.isEmpty(rechargeModel.getPay_info().getPay_url())) {
                    dialogView = getLayoutInflater().inflate(R.layout.wx_buy, null);
                    builder.setView(dialogView);
                    mPaydialogProgress = builder.create();
                    mPaydialogProgress.setCancelable(true);
                    mPaydialogProgress.show();
                    AppCompatImageView imgCode = dialogView.findViewById(R.id.img_code);
                    Glide.with(getContext()).load(rechargeModel.getPay_info().getPay_url()).into(imgCode);
                } else {
                    if (rechargeModel.getState() == 2) {
                        Toast.makeText(getContext(), "充值成功", Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(getContext(), "充值失败", Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            public void onError(Response<LzyResponse<RechargeModel>> response) {
                super.onError(response);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEvent(EventMessage eventMsg) {
        switch (eventMsg.getMessage()) {
            case EventContent.class_works_date://刷新支付信息
                break;
            case EventContent.pay_ok://支付成功
                mPaydialogProgress.dismiss();
                ToastUtil.toastShortMessage("余额充值成功");
                mPaydialogProgress.dismiss();
                dialogProgress.dismiss();
                getWalletInfoDate();
                break;
            case EventContent.upDate_user:
                break;
        }
    }

    /**
     * 充值记录页面逻辑处理
     */
    private void setupRechargePage(View view) {
        mRechargeAmountRecyclerView = view.findViewById(R.id.rl_recharge_record);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mRechargeAmountRecyclerView.setLayoutManager(layoutManager);
        mRechargeRecordAdapter = new RechargeRecordAdapter();
        mRechargeAmountRecyclerView.setAdapter(mRechargeRecordAdapter);
        rechargeSwipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        tvNoRecord = view.findViewById(R.id.tv_no_record);
        rechargeSwipeRefreshLayout.setRefreshing(true);
        rechargeSwipeRefreshLayout.setOnRefreshListener(() -> {
                    Content.page = 1;
                    getRechargeAmountDate();
                }
                );
        getRechargeAmountDate();
    }

    private void getRechargeAmountDate() {
        List<String> searchType = Arrays.asList("3");
        OkGo.<LzyResponse<OrderListModel>>get(Urls.ORDER_LIST)
                .addUrlParams("search_type",searchType)
                .params("page", Content.page)
                .params("limit", Content.limit)
                .execute(new JsonCallback<LzyResponse<OrderListModel>>() {

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onSuccess(Response<LzyResponse<OrderListModel>> response) {
                OrderListModel oriderListModel = response.body().data;
                if (!oriderListModel.getOrder_list().isEmpty()) {
                    rechargeSwipeRefreshLayout.setVisibility(View.VISIBLE);
                    tvNoRecord.setVisibility(View.GONE);
                } else {
                    tvNoRecord.setVisibility(View.VISIBLE);
                    rechargeSwipeRefreshLayout.setVisibility(View.GONE);
                }
                new Handler(Looper.getMainLooper()).post(() ->{
                    mRechargeRecordAdapter.addData(oriderListModel);
                    mRechargeAmountRecyclerView.setAdapter(mRechargeRecordAdapter);
                });
                rechargeSwipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onError(Response<LzyResponse<OrderListModel>> response) {
                super.onError(response);
                rechargeSwipeRefreshLayout.setRefreshing(false);

            }
        });

    }

    /**
     * 提现记录页面逻辑处理
     */
    private void setupWithdrawPage(View view) {
        withDrawalRecyclerView = view.findViewById(R.id.rl_withdrawal_record);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        withDrawalRecyclerView.setLayoutManager(layoutManager);
        withDrawalRecordAdapter = new WithDrawalRecordAdapter();
        withDrawalSwipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        tvWithDrawalNoRecord = view.findViewById(R.id.tv_no_record);
        withDrawalSwipeRefreshLayout.setRefreshing(true);
        withDrawalSwipeRefreshLayout.setOnRefreshListener(() -> getWithDrawalInfoDate());
        getWithDrawalInfoDate();
    }

    /**
     * 钱包页面信息展示
     * */
    private void getWalletInfoDate() {
        OkGo.<LzyResponse<WalletModel>>get(Urls.USER_WALLET).execute(new JsonCallback<LzyResponse<WalletModel>>() {

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(Response<LzyResponse<WalletModel>> response) {
                WalletModel walletModel = response.body().data;
                if (walletModel.getUserWallet() == null) {
                    return;
                }
                withdrawableBalance.setText(walletModel.getUserWallet().getBalance()/100 + "");
                pendingBalance.setText(walletModel.getUserWallet().getPending()/100 + "");
                frozenBalance.setText(walletModel.getUserWallet().getFreezeBalance()/100 + "");
                coinBalance.setText(walletModel.getUserWallet().getVirtualCoin()/100 + "");
                virtualCoins = walletModel.getUserWallet().getVirtualCoin()/100;
                accumulateWithDrawnAmount.setText(walletModel.getUserWallet().getWithdrawalToal()/100 + "");
                balance.setText(walletModel.getUserWallet().getBalanceTotal()/100 + "");
                if (walletModel.getUserBindInfo() == null) {
                    wechatName.setText("微信账号");
                    return;
                }
                if (walletModel.getUserBindInfo().getWxOpenid() != null) {
                    wechatName.setText("已绑定");
                } else {
                    wechatName.setText("微信账号");
                }

            }

            @Override
            public void onError(Response<LzyResponse<WalletModel>> response) {
                super.onError(response);
            }
        });
    }

    @Override
    public void onRechargeAmountSelected(int id, int type, int price, int gift, int value, String rechargeAmount) {
        if (type == 2) {
            String formattedText = String.format(requireContext().getString(R.string.bug_token_describe), price, value + gift);
            mTokenDescribe.setText(Html.fromHtml(formattedText));
        }
        mRechargeAmountId = id;
        mRechargeAmount = rechargeAmount;
    }

    /**
     * 申请提现
     * */
    private void withDrawablePay(String withAmount) {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("balance", withAmount);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse<String>>post(Urls.WITHDRAWAL_APPLY).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<String>>() {
            @Override
            public void onSuccess(Response<LzyResponse<String>> response) {
                ToastUtil.toastLongMessage("申请提现成功");
                dialogProgress.dismiss();
                getWalletInfoDate();
            }

            @Override
            public void onError(Response<LzyResponse<String>> response) {
                super.onError(response);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        getWalletInfoDate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }

    @Override
    public void refreshContent() {
        switch (position) {
            case 0:
                getWalletInfoDate();
                break;
            case 1:
                setupRechargePage(walletPageFragment);
                break;
            case 2:
                setupWithdrawPage(walletPageFragment);
                break;
        }
    }
}
